#encoding=utf8
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.core.urlresolvers import *
from django.http import *
from django.shortcuts import *
import json
from utils.JsonResponse import JsonResponse, JsonResponseBadrequest

from trp.models import *

def main(request):
    if request.user is None or not request.user.is_authenticated():
        return render_to_response("trp/login.html")
    return HttpResponseRedirect('/trp/index/')

def do_login(request):
    param= request.POST
    if param is None:
        return HttpResponseRedirect('/trp/index/')
    succ,username,remember = __do_login(request,param)
    if not succ :
        return render_to_response("trp/login.html", {'username': username, 'remember': remember})
    else :
        operation_log=OperationLog()
        operation_log.operation="登陆"
        operation_log.object="用户"
        operation_log.user=request.user     
        operation_log.object_id=request.user.id         
        operation_log.save()
        return HttpResponseRedirect('/trp/index/')

def do_login_ajax(request):
    param = json.loads(request.body)
    succ,username,remember = __do_login(request,param)
    if succ :
        return JsonResponse({"message":"ok"})
    else :
        return JsonResponseBadrequest({"message":"fail",'username': username, 'remember': remember})
    
def __do_login(request,param):
    """
    登录逻辑，返回三元组(登录状态true or false，username,remember)
    """
    username = param.get('username', '')
    password = param.get('password', '')
    remember = 0
    try:
        remember = int(param.get('remember', '0'))
    except:
        remember = 0
    user = authenticate(username=username, password=password)
    if user is None or user.account is None or user.account.deleted:
        return (False,username,remember)
    login(request, user)
    if remember != 1:
        request.session.set_expiry(24*60*60)
    else:
        request.session.set_expiry(None)
    return (True,username,remember)

def do_logout(request):
    if request.user != None and request.user.id!=None:
        operation_log=OperationLog()
        operation_log.operation="退出"
        operation_log.object="用户"
        operation_log.user=request.user  
        operation_log.object_id=request.user.id             
        operation_log.save()
        logout(request)    
    return HttpResponseRedirect('/trp/login/')

def page_not_found(request):
    return render_to_response('trp/notfound.html')

def page_error(request):
    return render_to_response('trp/error.html')
